%% 使用 double 数据进行 RPC 模型拟合, 截断为 single, 使用single测试数据验证
%
% 结论:
%   SVD和LC拟合精度均损失到0.1至0.2个像素附近

close all;
clear;

id = 4;
is_single = true;
mark_single = 'd';

dat_path = sprintf('datas/%02d/resamp_verify_%02d.dat', id, id);
rpc_svd_path = sprintf('datas/%02d/svd_%02d_%c.rpc', id, id, mark_single);
rpc_lc_path = sprintf('datas/%02d/lc_%02d_%c.rpc', id, id, mark_single);

%%

[vgcp_x, vgcp_y, vgcp_z, vgcp_col, vgcp_row, img_size] = loadResampDat(dat_path);

if is_single
    vgcp_x = single(vgcp_x);
    vgcp_y = single(vgcp_y);
    vgcp_z = single(vgcp_z);
    vgcp_col = single(vgcp_col);
    vgcp_row = single(vgcp_row);
end


%%
rpc_model_svd = hsRPC.read(rpc_svd_path);
if is_single
    rpc_model_svd = rpc2single(rpc_model_svd);
end

[est_col, est_row] = hsRPC.project(rpc_model_svd, vgcp_x, vgcp_y, vgcp_z);
error_col_svd = est_col - vgcp_col;
error_row_svd = est_row - vgcp_row;

figure;
subplot(211);
plot(error_col_svd);
title("SVD error x");
grid on;
subplot(212);
plot(error_row_svd);
title("SVD error y");
grid on;

%%
rpc_model_lc = hsRPC.read(rpc_lc_path);
if is_single
    rpc_model_lc = rpc2single(rpc_model_lc);
end

[est_col, est_row] = hsRPC.project(rpc_model_lc, vgcp_x, vgcp_y, vgcp_z);
error_col_lc = est_col - vgcp_col;
error_row_lc = est_row - vgcp_row;

figure;
subplot(211);
plot(error_col_lc);
title("LC error x");
grid on;
subplot(212);
plot(error_row_lc);
title("LC error y");
grid on;

%%
function rpc_st = rpc2single(rpc_st)
    keys = fieldnames(rpc_st);
    for i = 1:numel(keys)
        if isnumeric(rpc_st.(keys{i}))
            rpc_st.(keys{i}) = single(rpc_st.(keys{i}));
        end
    end
end
